package net.piggy.spring;

import net.piggy.core.Mediator;
import net.piggy.domain.MethodBean;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import net.piggy.anno.Remote;

import java.lang.reflect.Method;
import java.util.Map;

@Component
public class NettyApplicationListener implements ApplicationListener<ContextRefreshedEvent>, Ordered {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {

        Map<String, Object> beansWithAnnotation = contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(Remote.class);

        for(String key : beansWithAnnotation.keySet()){
            // key --> Name / value -->Object
            Object bean = beansWithAnnotation.get(key);
            Method[] declaredMethods = bean.getClass().getDeclaredMethods();
            for(Method method:declaredMethods){
                // function
                String methodAllName = bean.getClass().getInterfaces()[0].getName() + "." + method.getName();
                MethodBean methodBean = new MethodBean();
                methodBean.setBean(bean);
                methodBean.setMethod(method);
                Mediator.methodBeans.put(methodAllName,methodBean);
            }
        }
    }

    @Override
    public int getOrder() {
        return -1;
    }


}
